package com.chatplus.application.controller.admin.file;

import com.chatplus.application.common.domain.response.PayloadOnlyResponse;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.domain.vo.file.UpLoadFileVo;
import com.chatplus.application.service.file.FileService;
import com.google.common.collect.Lists;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * 文件相关控制机器
 *
 * @author LY
 */

@RestController
@RequestMapping("/file")
public class FileController{

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(FileController.class);


    private FileService fileService;

    @Autowired
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 图片上传接口
     *
     * @param srcFiles 文件
     */
    @PostMapping("/upload")
    public PayloadOnlyResponse upload(@RequestParam("files") MultipartFile[] srcFiles) {
        List<UpLoadFileVo> resultList = Lists.newArrayList();
        for (MultipartFile srcFile : srcFiles) {
            Date date = new Date();
            UpLoadFileVo vo = fileService.uploadFileSDK(srcFile);
            vo.setUploadedAt(date);
            if (!Boolean.TRUE.equals(vo.getSuccess())) {
                throw new BadRequestException("图片上传失败，请稍后再试");
            }
            resultList.add(vo);
        }
        return new PayloadOnlyResponse(resultList);
    }

}
